package fi.foyt.cs.persistence.dao.scene;

import javax.persistence.EntityManager;
import javax.persistence.Query;

import fi.foyt.cs.persistence.dao.GenericDAO;
import fi.foyt.cs.persistence.domainmodel.scene.Scene;
import fi.foyt.cs.persistence.domainmodel.scene.SceneType;

public class SceneDAO extends GenericDAO<Scene> {

  public Scene create(Long categoryId, SceneType type, String externalId) {
    EntityManager entityManager = getEntityManager();

    entityManager.getTransaction().begin();
    try {
      Scene scene = new Scene();
      scene.setType(type);
      scene.setExternalId(externalId);
      scene.setCategoryId(categoryId);
      entityManager.persist(scene);
      entityManager.getTransaction().commit();
      return scene;
    } finally {
      if (entityManager.getTransaction().isActive())
        entityManager.getTransaction().rollback();
    }
  }

  public Scene findById(Long id) {
    EntityManager entityManager = getEntityManager();
    return entityManager.find(Scene.class, id);
  }

  public Scene findByTypeAndExternalId(SceneType type, String externalId) {
    EntityManager entityManager = getEntityManager();
    Query query = entityManager.createQuery("select s from Scene s where s.type = :type and s.externalId = :externalId");
    query.setParameter("type", type.toString());
    query.setParameter("externalId", externalId);
    return getSingleResult(query);
  }
}